package com.ncmmall.application.util;

import com.feijin.commons.exceptions.InterfaceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 发送请求
 *
 * @author 90
 */
@Slf4j
public final class HttpRequests {

    public static String get(String url) {
        try {
            return Request.Get(url).execute().returnContent().asString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new InterfaceException("[非200响应码]");
        }
    }

    /**
     * @param url         request url
     * @param data        xml or json
     * @param contentType application/xml application/json
     */
    public static String postEntity(String url, String data, String contentType) {
        try {
            return Request.Post(url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, contentType)
                    .body(new StringEntity(data, "utf-8"))
                    .execute()
                    .returnContent()
                    .asString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new InterfaceException("[非200响应码]");
        }
    }

    public static String postEntity(String url, List<NameValuePair> nameValuePairs) {
        try {
            return Request.Post(url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType())
                    .bodyForm(nameValuePairs)
                    .execute()
                    .returnContent()
                    .asString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new InterfaceException("[非200响应码]");
        }
    }
}
